package com.qianfeng.qlm.handforireader.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.qianfeng.qlm.handforireader.R;
import com.qianfeng.qlm.handforireader.adapter.NewChapterRecycleAdapter;
import com.qianfeng.qlm.handforireader.model.Cartoon;
import com.qianfeng.qlm.handforireader.model.CategoryDetail;
import com.qianfeng.qlm.handforireader.model.NewChapter;
import com.qianfeng.qlm.handforireader.model.NewChapterList;
import com.qianfeng.qlm.handforireader.util.UrlMaker;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class NewChapterActivity extends ActionBarActivity implements View.OnClickListener {

    private RecyclerView recyclerView;
    private ArrayList<NewChapter> data;
    private String url;
    private NewChapterRecycleAdapter adapter;
    private String comicName;
    private RelativeLayout rlLoading;
    private ImageView imgLoading;
    private AnimationDrawable animationDrawable;
    private TextView txtShare;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_chapter);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        Intent name = getIntent();
        comicName = name.getStringExtra("name");
        actionBar.setTitle(comicName);

        recyclerView = (RecyclerView) findViewById(R.id.recyler_view);

        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layout);
        data = new ArrayList<>();
        adapter = new NewChapterRecycleAdapter(this, data);
        recyclerView.setAdapter(adapter);

        rlLoading = (RelativeLayout)findViewById(R.id.rl_loading);
        imgLoading = (ImageView) findViewById(R.id.new_chapter_loading_img);

        txtShare = (TextView) findViewById(R.id.activity_chapter_share);
        txtShare.setOnClickListener(this);

        Intent intent = getIntent();
        if (intent != null){
            url = intent.getStringExtra("url");
            initRequest();
        }


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId){
            case android.R.id.home:
                finish();
                break;
            case R.id.action_favorite:
                Intent intent = getIntent();
                Bundle extras = intent.getExtras();
                CategoryDetail comic = (CategoryDetail) extras.getSerializable("comic");
                addToFavorite(comic);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void addToFavorite(CategoryDetail comic) {
        DbUtils db = DbUtils.create(this);
        Cartoon cartoon = new Cartoon();
        cartoon.setId(comic.getId());
        cartoon.setPainter_user_nickname(comic.getPainter_user_nickname());
        cartoon.setComic_name(comic.getComic_name());
        cartoon.setComic_desc(comic.getComic_desc());
        cartoon.setComic_pic_240_320(comic.getComic_pic_240_320());
        cartoon.setComic_last_orderidx(comic.getComic_last_orderidx());
//        cartoon.setUrl(url);
        try {
            db.save(cartoon);
        } catch (DbException e) {
            e.printStackTrace();
        }

        Toast.makeText(this,"已添加至收藏", Toast.LENGTH_SHORT).show();

        try {
            List<Cartoon> cartoonList = db.findAll(Cartoon.class);
            Log.d("DataBase",cartoonList.toString());
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_content_list_view,menu);
        return true;
    }

    private void initRequest(){
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest request = new JsonObjectRequest(
                url,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null){
                            animationDrawable.stop();
                            rlLoading.setVisibility(View.GONE);
                            NewChapterList newChapterList = new NewChapterList();
                            newChapterList.parseJson(response);
                            adapter.setData(newChapterList.getNewChapterList());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }
        );

        animationDrawable = (AnimationDrawable) imgLoading.getDrawable();
        animationDrawable.start();
        requestQueue.add(request);
    }

    @Override
    public void onClick(View v) {


        int id = v.getId();
        if (id == R.id.activity_chapter_share){
            shareContent(this);
            return;
        }

        int position = recyclerView.getChildPosition(v);

        List<NewChapter> adapterData = adapter.getData();
        NewChapter newChapter = adapterData.get(position);
        String comicId = newChapter.getComic_id();
        String orderIdx = newChapter.getOrder_idx();
        String contentUrl = UrlMaker.GetComicContent(comicId, orderIdx);
        Intent intent = new Intent(this,ContentListActivity.class);
        intent.putExtra("url",contentUrl);
        intent.putExtra("name",data.get(position).getOrder_name());
        startActivity(intent);

    }

    private void shareContent(Context context){
        ShareSDK.initSDK(context);

        OnekeyShare oks = new OnekeyShare();
        oks.setText("分享测试jason");
        oks.setNotification(R.mipmap.ic_launcher,"休闲漫画");
        oks.setImageUrl("http://r.qingman.cc/Public/Images/qingman/active/item/active1.jpg");
        oks.show(context);
    }
}
